package main

import (
	"fmt"
	"github.com/golang/glog"
	"io"
	"log"
	"net"
	"net/http"
	_ "net/http/pprof"
	"os"
)

func main() {

	// 打印日志
	glog.V(2).Info("Starting http server...")

	// 获取环境变量
	version := os.Getenv("VERSION")
	if version == "" {
		os.Setenv("VERSION", "1.0.0")
	}

	// 设置一个 path 和 handler 的映射
	http.HandleFunc("/", rootHandler)
	http.HandleFunc("/healthz", healthz)

	// 起一个 server，在 80 端口监听
	err := http.ListenAndServe(":8088", nil)

	if err != nil {
		log.Fatal(err)
	}

}

func healthz(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "ok\n")
}

func rootHandler(w http.ResponseWriter, r *http.Request) {

	fmt.Println("entering root handler")

	// 1.获取 request header，并写入 response header
	for k, v := range r.Header {
		var value string = ""
		for _, s := range v {
			value += s
			value += ","
		}
		w.Header().Set(k, value)
	}

	// 2.获取环境变量 VERSION，并写入 response header
	version := os.Getenv("VERSION")
	if version != "" {
		w.Header().Set("VERSION", version)
	}

	// 3.1 获取本机 ip
	ip := RemoteIp(r)

	// 3.2 日志打印本机 ip
	glog.Info(ip)

	w.WriteHeader(200)

	// 3.3 输出本机 ip 到标准输出
	io.WriteString(w, fmt.Sprintf("IP [%s]\n", ip))
}

func RemoteIp(req *http.Request) string {
	remoteAddr := req.RemoteAddr
	if ip := req.Header.Get("X-Read-IP"); ip != "" {
		remoteAddr = ip
	} else if ip = req.Header.Get("X-Forwarded-For"); ip != "" {
		remoteAddr = ip
	} else {
		remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
	}

	if remoteAddr == "::1" {
		remoteAddr = "127.0.0.1"
	}

	return remoteAddr
}